package org.multithreadprint;

import java.util.concurrent.CountDownLatch;

/**
 * Copyright (c) 2023-2033 All Rights Reserved
 * CountDownLatch 实现计数器的功能
 * 1. 构造函数初始化，传入计数器初始值
 * 2. countDown()方法执行后计数 -1
 * 3. await() 等待计数为 0 后才执行
 *
 * https://bbs.huaweicloud.com/blogs/336562
 * https://blog.csdn.net/Evankaka/article/details/80800081
 * @date: 2023/7/17
 */
public class MultiThreadCountDownLatch {
    public static void main(String[] args) {
        CountDownLatch countDownLatch0 = new CountDownLatch(0);
        CountDownLatch countDownLatch1 = new CountDownLatch(1);
        CountDownLatch countDownLatch2 = new CountDownLatch(1);

        Thread threadA = new Thread(() -> {
            try {
                countDownLatch0.await(); // 在 CD = 0 后执行
                System.out.println("A");
                countDownLatch1.countDown();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

        Thread threadB = new Thread(() -> {
            try {
                countDownLatch1.await();
                System.out.println("B");
                countDownLatch2.countDown();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

        Thread threadC = new Thread(() -> {
            try {
                countDownLatch2.await();
                System.out.println("C");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

        threadC.start();
        threadB.start();
        threadA.start();
    }
}
